package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 调用那些与当前类Test9在同一个保重被注解@AutoRunClass标注的类里所有被注解@AutoRunMethod
 * 标注的方法
 */
public class Test9 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        String pack = Test9.class.getPackage().getName();

        File dir = new File(
                Test9.class.getResource(".").toURI()
        );
        File[] suds = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sud : suds) {
            String fileName = sud.getName();
            String className = fileName.replace(".class", "");
            Class cls = Class.forName(pack + "." + className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                System.out.println("实例化:" + className);
                Object obj = cls.newInstance();
                System.out.println(obj);

                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        System.out.println("执行方法:" + method.getName() + "()");
                        method.invoke(obj);
                    }
                }

            }
        }
    }
}
